'use strict'

import { app, BrowserWindow, Menu, ipcMain, dialog } from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

let sender
const template = [
  {
    id: 'file',
    label: '文件',
    submenu: [
      {
        label: '新建窗口',
        accelerator: 'CommandOrControl+Shift+N',
        click: (menuItem, browserWindow, event) => {
          createWindow()
        }
      },
      {
        label: '新建文件',
        accelerator: 'CommandOrControl+N',
        click: (menuItem, browserWindow, event) => {
          sender.send('new-file')
        }
      },
      { type: 'separator' },
      {
        label: '打开文件',
        accelerator: 'CommandOrControl+O',
        click: () => {
          dialog.showOpenDialog({
            title: '打开文件',
            filters: [
              {name: 'Markdowns', extensions: ['md']}
            ],
            properties: ['openFile']
          }, (files) => {
            sender.send('open-file', files)
          })
        }
      },
      {
        id: 'openFileRecord',
        label: '打开最近文件',
        submenu: [{
          label: '测试',
          click: (menuItem, browserWindow, event) => {
            console.log('测试')
          }
        }]
      },
      { type: 'separator' },
      { role: 'quit', label: '退出' }
    ]
  },
  {
    label: 'Edit',
    submenu: [
      {role: 'undo'},
      {role: 'redo'},
      {type: 'separator'},
      {role: 'cut'},
      {role: 'copy'},
      {role: 'paste'},
      {role: 'pasteandmatchstyle'},
      {role: 'delete'},
      {role: 'selectall'}
    ]
  },
  {
    label: 'View',
    submenu: [
      {role: 'reload'},
      {role: 'forcereload'},
      {role: 'toggledevtools'},
      {type: 'separator'},
      {role: 'resetzoom'},
      {role: 'zoomin'},
      {role: 'zoomout'},
      {type: 'separator'},
      {role: 'togglefullscreen'}
    ]
  },
  {
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click () { require('electron').shell.openExternal('https://electron.atom.io') }
      }
    ]
  }
]

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    width: 1000
  })

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)

  // 右键菜单
  ipcMain.on('show-context-menu', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    menu.popup(win)
  })

  // 菜单事件
  ipcMain.on('menu-file', (event, args) => {
    sender = event.sender
  })

  // 最近打开记录
  ipcMain.on('open-file-record', (event, args) => {
    let openFileRecord = args
    template.forEach(item1 => {
      if (item1.id === 'file') {
        item1.submenu.forEach(item2 => {
          if (item2.id === 'openFileRecord') {
            let submenu = []
            openFileRecord.forEach(file => {
              submenu.push({
                label: file.filename,
                click: (menuItem, browserWindow, event) => {
                  sender.send('open-file', file.src)
                }
              })
            })
            item2.submenu = submenu
          }
        })
      }
    })
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
